package com.jcsz.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jcsz.common.constant.CartConstant;
import com.jcsz.common.exception.NoStockException;
import com.jcsz.common.to.SkuHasStockVo;
import com.jcsz.common.to.mq.OrderTo;
import com.jcsz.common.to.mq.SeckillOrderTo;
import com.jcsz.common.utils.R;
import com.jcsz.common.vo.MemberRespVo;
import com.jcsz.gulimall.order.constant.OrderConstant;
import com.jcsz.gulimall.order.constant.PayConstant;
import com.jcsz.gulimall.order.entity.OrderItemEntity;
import com.jcsz.gulimall.order.entity.OrderReturnReasonEntity;
import com.jcsz.gulimall.order.entity.PaymentInfoEntity;
import com.jcsz.gulimall.order.enume.OrderStatusEnum;
import com.jcsz.gulimall.order.feign.CartFeignService;
import com.jcsz.gulimall.order.feign.MemberFeignService;
import com.jcsz.gulimall.order.feign.WareFeignService;
import com.jcsz.gulimall.order.feign.productFeignService;
import com.jcsz.gulimall.order.interceptor.LoginInterceptor;
import com.jcsz.gulimall.order.service.OrderItemService;
import com.jcsz.gulimall.order.service.PaymentInfoService;
import com.jcsz.gulimall.order.to.OrderCreateTo;
import com.jcsz.gulimall.order.vo.*;
import com.rabbitmq.client.Channel;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.order.dao.OrderDao;
import com.jcsz.gulimall.order.entity.OrderEntity;
import com.jcsz.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
@Slf4j
//@RabbitListener(queues = {"my_queue"})
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    productFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();// 获取当前登录后的用户
        // 异步任务执行之前，先共享数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        System.out.println("主线程:" + Thread.currentThread().getId());
        // 1、第一个异步任务 远程查询用户地址信息
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            //   根据会员id查出之前会员保存过的收货地址信息
            //   远程查询会员服务的收获地址信息
            System.out.println("memberFuture:" + Thread.currentThread().getId());
            // 在主线程中拿到原来的数据，在父线程里面共享RequestContextHolder
            // 只有共享，拦截其中才会有数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 根据会员id查出之前会员保存过的收货地址信息
            // 远程查询会员服务的收获地址信息
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, threadPoolExecutor);

        // 2、第二个异步任务远程查询购物车中选中给的购物项
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //  远程查询购物车中的购物项信息，用来结账
            System.out.println("cartFuture:" + Thread.currentThread().getId());
            // 每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询购物车中的购物项信息，用来结账
            List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();// 获取当前用户的购物项数据
            log.info("currentUserCartItem:{}", currentUserCartItem);
            orderConfirmVo.setItem(currentUserCartItem);
        }, threadPoolExecutor).thenRunAsync(() -> { // 只要上面任务执行完成，就开始执行thenRunAsync的任务
            // 3、商品是否有库存
            List<OrderItemVo> items = orderConfirmVo.getItem();
            // 批量查询每一个商品的信息
            // 收集好商品id
            List<Long> skuIds = items.stream().map((obj) -> obj.getSkuId()).collect(Collectors.toList());
            // 远程查询购物项对应的库存信息
            R r = wareFeignService.getSkuHasStocks(skuIds);
            // 得到每一个商品的库存状态信息
            List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> stockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(stockMap);
            }
        }, threadPoolExecutor);
        CompletableFuture.allOf(memberFuture, cartFuture).get();
        //积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //防重令牌
        String token = UUID.randomUUID().toString();
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        return orderConfirmVo;
    }

    @Override
    @Transactional
    //@GlobalTransactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        // 先将参数放到共享变量中，方便之后方法使用该参数
        confirmVoThreadLocal.set(orderSubmitVo);
        // 通过拦截器拿到用户的数据
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();// 获取当前登录后的用户

        // 接收返回数据
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        //获取页面令牌
        String orderToken = orderSubmitVo.getOrderToken();
        // 验证令牌【令牌的对比和删除必须保证原子性】
        // 因此使用redis中脚本来进行验证并删除令牌
        // 0【删除失败/验证失败】 1【删除成功】
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            // 验证失败直接返回结果
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 原子验证令牌成功
            // 下单 创建订单、验证令牌、验证价格、验证库存
            // 1、创建订单、订单项信息
            OrderCreateTo orderCreateTo = createOrder();
            // 2、应付总额
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            // 应付价格
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            /**
             * 电商项目对付款的金额精确到小数点后面两位
             * 订单创建好的应付总额 和购物车中计算好的应付价格求出绝对值。
             */
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //TODO 3、保存订单&订单详情
                saveOrder(orderCreateTo);
                //4、库存锁定,只要有异常，回滚订单数据
                //订单号、所有订单项信息(skuId,skuNum,skuName)
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(orderCreateTo.getOrder().getOrderSn());
                List<OrderItemVo> collect = orderCreateTo.getOrderItem().stream().map((item) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                //TODO 调用远程锁定库存的方法
                //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
                //为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 200) {
                    //锁定成功
                    responseVo.setOrder(orderCreateTo.getOrder());
                    //int i = 10 / 0;//订单回滚,库存不回滚

                    //TODO 库存锁定,订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderCreateTo.getOrder());

                    //删除购物车里的数据
                    //redisTemplate.delete(CartConstant.CART_PREFIX+memberRespVo.getId());
                    return responseVo;
                } else {
                    throw new NoStockException((String) r.get("msg"));
                    //responseVo.setCode(3);
                    //return responseVo;
                }
            } else {
                responseVo.setCode(2);//订单商品价格发生变化，请确认后再次提交
                return responseVo;
            }
        }
    }


    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        save(order);
        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItem();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1、生成订单号
        String orderId = IdWorker.getTimeId();
        // 2、构建订单
        OrderEntity orderEntity = buildOrder(orderId);
        // 3、构建订单项
        List<OrderItemEntity> itemEntities = builderOrderItems(orderId);
        // 4、设置价格、积分相关信息
        computPrice(orderEntity, itemEntities);
        // 5、设置订单项
        orderCreateTo.setOrderItem(itemEntities);
        // 6、设置订单
        orderCreateTo.setOrder(orderEntity);
        return orderCreateTo;
    }

    private void computPrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        // 1、定义好相关金额，然后遍历购物项进行计算
        // 总价格
        BigDecimal total = new BigDecimal("0");
        //相关优惠信息
        // 优惠卷抵扣金额
        BigDecimal coupon = new BigDecimal("0");
        // 积分优惠金额
        BigDecimal integration = new BigDecimal("0");
        // 促销优惠金额
        BigDecimal promotion = new BigDecimal("0");
        // 积分
        BigDecimal gift = new BigDecimal("0");
        // 成长值
        BigDecimal growth = new BigDecimal("0");

        for (OrderItemEntity itemEntity : itemEntities) {
            coupon = coupon.add(itemEntity.getCouponAmount()); // 优惠卷抵扣
            integration = integration.add(itemEntity.getIntegrationAmount()); // 积分优惠分解金额
            promotion = promotion.add(itemEntity.getPromotionAmount()); // 商品促销分解金额
            gift = gift.add(new BigDecimal(itemEntity.getGiftIntegration().toString())); // 赠送积分
            growth = growth.add(new BigDecimal(itemEntity.getGiftGrowth())); // 赠送成长值
            total = total.add(itemEntity.getRealAmount()); //优惠后的总金额
        }
        // 2、设置订单金额
        // 订单总金额
        orderEntity.setTotalAmount(total);
        // 应付总额 = 订单总额 + 运费信息
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        // 促销优化金额（促销价、满减、阶梯价）
        orderEntity.setPromotionAmount(promotion);
        // 优惠券抵扣金额
        orderEntity.setCouponAmount(coupon);

        // 3、设置积分信息
        // 订单购买后可以获得的成长值
        orderEntity.setGrowth(growth.intValue());
        // 积分抵扣金额
        orderEntity.setIntegrationAmount(integration);
        // 可以获得的积分
        orderEntity.setIntegration(gift.intValue());
        // 删除状态【0->未删除；1->已删除】
        orderEntity.setDeleteStatus(0);
    }

    private List<OrderItemEntity> builderOrderItems(String orderId) {
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem.size() > 0 && currentUserCartItem != null) {
            List<OrderItemEntity> collect = currentUserCartItem.stream().map((item) -> {
                OrderItemEntity itemEntity = builderOrderItem(item);
                itemEntity.setOrderSn(orderId);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity builderOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        //设置spu信息
        itemEntity.setSpuId(spuInfo.getId());
        itemEntity.setSpuName(spuInfo.getSpuName());
        itemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        //分类
        itemEntity.setCategoryId(spuInfo.getCatalogId());
        //设置sku信息
        itemEntity.setSkuId(skuId); // skuid
        itemEntity.setSkuName(cartItem.getTitle()); // 商品标题
        itemEntity.setSkuPrice(cartItem.getPrice());// 商品sku价格
        // 商品属性以 ; 拆分
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuPic(cartItem.getImage());     // 商品图片
        itemEntity.setSkuQuantity(cartItem.getCount());  // 商品购买数量

        // 4、设置商品优惠信息【不做】
        // 5、设置商品积分信息
        // 赠送积分 移弃小数值
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        // 赠送成长值
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        // 6、订单项的价格信息
        // 这里需要计算商品的分解信息
        // 商品促销分解金额
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        // 优惠券优惠分解金额
        itemEntity.setCouponAmount(new BigDecimal("0"));
        // 积分优惠分解金额
        itemEntity.setIntegrationAmount(new BigDecimal("0"));

        // 商品价格乘以商品购买数量=总金额(未包含优惠信息)
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        // 总价格减去优惠卷-积分优惠-商品促销金额 = 总金额
        origin.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        // 该商品经过优惠后的分解金额
        itemEntity.setRealAmount(origin);
        return itemEntity;
    }

    private OrderEntity buildOrder(String orderId) {
        //拿到共享数据
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        //获取用户登录数据
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderId);//订单号
        orderEntity.setMemberId(memberRespVo.getId());//用户Id
        //根据地址id查询收货地址信息
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo data = fare.getData(new TypeReference<FareVo>() {
        });
        //将查询到的会员收货地址信息设置到订单对象中
        // 运费金额
        orderEntity.setFreightAmount(data.getFare());
        // 城市
        orderEntity.setReceiverCity(data.getAddress().getCity());
        // 详细地区
        orderEntity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        // 收货人姓名
        orderEntity.setReceiverName(data.getAddress().getName());
        // 收货人手机号
        orderEntity.setReceiverPhone(data.getAddress().getPhone());
        // 区
        orderEntity.setReceiverRegion(data.getAddress().getRegion());
        // 省份直辖市
        orderEntity.setReceiverProvince(data.getAddress().getProvince());
        //自动确认收货时间
        orderEntity.setAutoConfirmDay(7);
        // 订单刚创建状态设置为 待付款，用户支付成功后将该该状态改成已付款
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //会员名
        orderEntity.setMemberUsername(memberRespVo.getUsername());

        return orderEntity;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void testRabbitMQSend() {
        for (int i = 1; i <= 5; i++) {
            OrderReturnReasonEntity reasonEntity = new OrderReturnReasonEntity();
            reasonEntity.setId(1l);
            reasonEntity.setCreateTime(new java.util.Date());
            reasonEntity.setName("哈哈");
            //
            String msg = "Hello World";
            // 发送的对象类型的消息，可以是一个json
            rabbitTemplate.convertAndSend("my_exchange", "hello.java", reasonEntity);
            log.info("消息发送完成{}");
        }

    }

    public void testRabbitMQSend2() {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                OrderReturnReasonEntity reasonEntity = new OrderReturnReasonEntity();
                reasonEntity.setId(1l);
                reasonEntity.setCreateTime(new java.util.Date());
                reasonEntity.setName("哈哈");
                //
                String msg = "Hello World";
                // 发送的对象类型的消息，可以是一个json
                rabbitTemplate.convertAndSend("my_exchange", "hello.java", reasonEntity);
            } else {
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setOrderSn(UUID.randomUUID().toString());
                rabbitTemplate.convertAndSend("my_exchange", "hello.java", orderEntity);
            }
            log.info("消息发送完成{}");
        }

    }

    @Override
    //@RabbitHandler
    public void testRabbitMQReceive(Message message, OrderReturnReasonEntity reasonEntity, Channel channel) throws IOException {
        System.out.println("收到....." + reasonEntity);
        byte[] body = message.getBody();
        MessageProperties messageProperties = message.getMessageProperties();
        // try { TimeUnit.MILLISECONDS.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}

        //System.out.println("消息处理完成.." + reasonEntity.getName());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (deliveryTag % 2 == 0) {
            channel.basicAck(deliveryTag, false);
            System.out.println("签收了:" + deliveryTag);
        } else {
            channel.basicNack(deliveryTag, false, false);
            System.out.println("未签收:" + deliveryTag);
        }


    }

    @Override
    //@RabbitHandler
    public void testRabbitMQReceive(Message message, OrderEntity orderEntity, Channel channel) {
        System.out.println("收到XXXX" + orderEntity);
        byte[] body = message.getBody();
        MessageProperties messageProperties = message.getMessageProperties();
        //System.out.println("消息处理完成XXX" + orderEntity.getOrderSn());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("deliveryTag:" + deliveryTag);
    }

    @Override
    public OrderEntity getInfoByOrderSn(String orderSn) {

        return baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void orderClose(OrderEntity orderEntity) {
        OrderEntity order = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));
        if (order.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity newOrder = new OrderEntity();
            newOrder.setOrderSn(order.getOrderSn());
            newOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            update(newOrder, new UpdateWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));

            //主动发消息解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            try {
                //TODO 确保每个消息发送成功，给每个消息做好日志记录，(给数据库保存每一个详细信息)保存每个消息的详细信息
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 定期扫描数据库，重新发送失败的消息
            }
        }
    }

    @Override
    public PayVo getPayVoByOrderSn(String orderSn) {
        OrderEntity order = getInfoByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        //保留两位小数点，向上取值
        BigDecimal payAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());

        //查询订单项的数据
        List<OrderItemEntity> orderItemInfo = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setSubject(orderItemEntity.getSkuName());
        return payVo;
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("create_time")
        );
        List<OrderEntity> orderEntities = page.getRecords().stream().map((order) -> {
            List<OrderItemEntity> orderItemEntityList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntityList);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);

    }

    @Transactional
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    /**
     * 修改订单状态
     *
     * @param orderSn
     * @param code
     */
    private void updateOrderStatus(String orderSn, Integer code, Integer payType) {

        this.baseMapper.updateOrderStatus(orderSn, code, payType);

    }

    //创建秒杀单
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = seckillOrderTo.getSeckillPrice().multiply(BigDecimal.valueOf(seckillOrderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(seckillOrderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuQuantity(seckillOrderTo.getNum());

        R r = productFeignService.getSkuInfoBySkuId(seckillOrderTo.getSkuId());
        if (r.getCode() == 200) {
            SkuInfoVo skuInfo = r.get("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            orderItem.setSkuPic(skuInfo.getSkuDefaultImg());
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(seckillOrderTo.getSkuId());
            if (skuSaleAttrValues.size() > 0 && skuSaleAttrValues != null) {
                String valuesString = StringUtils.collectionToDelimitedString(skuSaleAttrValues, ";");
                orderItem.setSkuAttrsVals(valuesString);
            }
            orderItem.setSkuName(skuInfo.getSkuName());
        }
        //保存订单项数据
        orderItemService.save(orderItem);
    }
}